    <template>
        <div class="transfer-edit-form">
            <div class="section">
                <h2 class="section-title">修改调拨单</h2>
                <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="trf_order" status-icon
                    :rules="rules" label-width="auto" class="demo-ruleForm">
                    <el-form-item label="调拨单号" prop="trf_code">
                        <el-input v-model="trf_order.trf_code" readonly />
                    </el-form-item>
                    <div style="display: flex; justify-content: space-between;">
                        <div style="width: 48%;">
                            <el-form-item label="调拨类型" prop="trf_type" style="margin-bottom: 30px;">
                                <el-select v-model="trf_order.trf_type" placeholder="请选择调拨类型"
                                    @change="handleSelectType">
                                    <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                        :value="item.dict_value" class="option-style" />
                                </el-select>
                            </el-form-item>

                            <el-form-item label="调出仓库" prop="warehouse_out_code" style="margin-bottom: 30px;">
                                <el-select v-model="trf_order.warehouse_out_code" placeholder="请选择调出仓库"
                                    @change="handleOutWarehouseChange" disabled>
                                    <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                        :label="item.warehouse_name" :value="item.warehouse_code" />
                                </el-select>
                            </el-form-item>


                        </div>

                        <div style="width: 48%;">
                            <el-form-item label="调拨日期" prop="trf_startdate" style="margin-bottom: 30px;">
                                <el-date-picker v-model="trf_order.trf_startdate" type="datetime" placeholder="选择日期时间"
                                    style="width: 100%;">

                                </el-date-picker>
                            </el-form-item>


                            <el-form-item label="调入仓库" prop="warehouse_enter_code" style="margin-bottom: 30px;">
                                <el-select v-model="trf_order.warehouse_enter_code" placeholder="请选择调入仓库"
                                    @change="handleEnterWarehouseChange">
                                    <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                        :label="item.warehouse_name" :value="item.warehouse_code" />
                                </el-select>
                            </el-form-item>


                        </div>
                    </div>
                </el-form>
            </div>

            <div class="section">
                <h2 class="section-title">调拨产品明细</h2>
                <div style="float: left;margin: 10px 0px;">
                    <el-button type="primary" @click="productAdd">添加</el-button>
                    <el-button @click="productDel">移除</el-button>
                </div>
                <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                    :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="stock_name" label="货品名称" fixed="left" width="150" />
                    <el-table-column prop="pro_code" label="货品编号" width="150" />
                    <el-table-column prop="pro_brand" label="品牌" width="100" />
                    <el-table-column prop="stock_model" label="规格型号" width="100" />
                    <el-table-column label="单位" width="70">
                        <template #default="scope">
                            <span>{{ measureValue(scope.row.dict_code) }}</span>
                        </template>
                    </el-table-column>




                    <el-table-column prop="stock_numder" label="当前库存" width="100" />

                    <el-table-column label="调拨数量" width="100">
                        <template #default="scope">
                            <el-input v-model="scope.row.transfer_qty" style="width: 75px" :precision="2" :min="0" />
                        </template>
                    </el-table-column>




                    <el-table-column prop="pro_cost_price" label="成本价" width="90" />
                    <el-table-column prop="pro_sale_price" label="销售价" width="110" />
                    <el-table-column label="成本合计" width="110">
                        <template #default="scope">
                            <span>{{ (scope.row.transfer_qty * scope.row.pro_cost_price).toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额合计" width="110">
                        <template #default="scope">
                            <span>{{ (scope.row.transfer_qty * scope.row.pro_sale_price).toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="height: 40px; line-height: 40px;">
                    <div style="display: inline-block; float: left;">合计</div>
                    <div style="display: inline-block; float:right">调拨总数量：{{ transfer_total_qty }}
                        &nbsp;&nbsp;&nbsp; 成本总额：{{ cost_total_price.toFixed(2) }}
                        &nbsp;&nbsp;&nbsp;金额总额：{{ amount_total_price.toFixed(2) }}
                    </div>
                </div>
            </div>

            <div class="button-group"
                style="position: absolute; bottom: 10px; right: 60.8px; display: flex; gap: 10px;">
                <el-button type="primary" @click="handleUpdate">保存修改</el-button>
                <el-button @click="handleClose">关闭</el-button>
            </div>
        </div>

        <!-- 添加产品模态框 -->
        <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
            <hr>
            <div style="margin: 10px 0px;">
                <div style="float: left;margin: 10px 0px;">
                    <el-input v-model="productcode" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                    <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                        <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                            :value="item.dict_value" />
                    </el-select>
                </div>
                <div style="float: right;margin: 10px 0px;">
                    <el-button @click="productReset">重置</el-button>
                    <el-button type="primary" @click="productSearch">查询</el-button>
                </div>
            </div>
            <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :selectable="isDisabled" />
                <el-table-column property="pro_code" label="货品编号" width="180" />
                <el-table-column property="stock_name" label="货品名称" width="200" />
                <el-table-column property="stock_model" label="规格型号" />
                <el-table-column label="单位">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column property="pro_cost_price" label="成本价" />
                <el-table-column property="pro_sale_price" label="销售价" />
                <el-table-column property="stock_numder" label="当前库存" />
            </el-table>
            <br>
            <div style="text-align: center;display: flex; justify-content: center;">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 20, 50]" :small="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" size="small" />
            </div>
            <hr>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </template>

    <script setup>
    import { ref, reactive, onMounted, inject, watch } from 'vue'
    import dayjs from 'dayjs'
    import axios from 'axios'
    import { useRouter } from 'vue-router';
    import { ElMessage } from 'element-plus';
    import { useWarehouseStore } from '@/storejs/warehouseStore'

    // 页面跳转获取数据
    const warehouseStore = useWarehouseStore()
    const trf_code = ref(warehouseStore.trf_code)

    // 仓库库区
    const outZones = ref([]);
    const enterZones = ref([]);

    // 仓库列表
    const warehouses = ref([]);

    // 调拨类型
    const options = ref([])

    // 调拨单对象
    let trfAdd = {
        trf_id: 0,
        trf_type: "",
        trf_code: "",
        trf_applicant: localStorage.getItem('userLName'),
        trf_startdate: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        trf_status: 0,
        warehouse_out_code: "",
        warehouse_out_name: "",
        warehouse_enter_code: "",
        warehouse_enter_name: "",
        update_by: localStorage.getItem('userLName'),
        update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
    }

    // 调拨单表单对象
    const trf_order = reactive({ ...trfAdd })

    const ruleFormRef = ref(null)
    const rules = reactive({});

    // 产品相关状态
    const dialogTableVisible = ref(false) // 控制添加产品模态框的显示/隐藏
    const productData = ref([])          // 存储从API获取的可添加产品列表
    const currentPage = ref(1)           // 产品列表的当前页码（用于分页）
    const pageSize = ref(5)              // 每页显示的产品数量（用于分页）
    const pageCount = ref(0)             // 产品总数（用于分页）

    const productcode = ref("")          // 产品搜索关键字（按名称或编号）
    const dict_code = ref("0")           // 按计量单位筛选产品的条件
    const measureOptios = ref([])        // 计量单位选项列表（从字典API获取）

    const multipleTableRef = ref(null);  // 产品选择表格的DOM引用（用于操作表格）
    const selectedProducts = ref([]);    // 在产品模态框中临时选中的产品（尚未确认添加）

    const selectedTable = ref(null);     // 已选产品表格的DOM引用（用于操作表格）
    const selectedRows = ref([]);        // 在已选产品表格中选中的行（用于删除操作）
    const selectedData = ref([]);        // 最终确认添加到调拨单中的产品列表

    // 调拨单统计信息
    const transfer_total_qty = ref(0)    // 调拨单中所有产品的调拨数量总和
    const cost_total_price = ref(0)      // 调拨单中所有产品的成本总价（成本价×数量）之和
    const amount_total_price = ref(0)    // 调拨单中所有产品的金额总和（销售价×数量）之和

    const router = useRouter()           // Vue Router实例，用于页面导航

    watch(selectedData, (newVal) => {
        transfer_total_qty.value = 0
        cost_total_price.value = 0
        amount_total_price.value = 0

        newVal.forEach(row => {
            if (isNaN(Number(row.transfer_qty))) {
                ElMessage.warning('调拨数量必须是数字');
                row.transfer_qty = 0;
            }

            if (row.transfer_qty > row.stock_numder) {
                ElMessage.warning('调拨数量不能大于当前库存');
                row.transfer_qty = row.stock_numder
            }

            // 计算总成本
            const cost = (row.transfer_qty || 0) * (row.pro_cost_price || 0);
            // 计算总金额
            const amount = (row.transfer_qty || 0) * (row.pro_sale_price || 0);

            transfer_total_qty.value += Number(row.transfer_qty)
            cost_total_price.value += cost
            amount_total_price.value += amount
        });
    }, { deep: true });

    // 点击修改按钮
    async function handleUpdate() {
        try {
            // 更新修改人和修改时间
            trf_order.update_by = localStorage.getItem('userLName');
            trf_order.update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ');

            // 转换明细数据
            const detailList = selectedData.value.map(item => ({
                trfproddtl_id: item.trfproddtl_id || 0,
                trf_id: trf_order.trf_id,
                pro_name: item.stock_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.stock_model,
                unitmeas_id: String(item.dict_code || ""),
                inventory_numder: Number(item.transfer_qty) || 0,
                pro_cost_price: Number(item.pro_cost_price),
                pro_sale_price: Number(item.pro_sale_price),
                out_location_code: item.out_location_code,
                out_location_name: item.out_location_name,
                enter_location_code: item.enter_location_code,
                enter_location_name: item.enter_location_name,
                Pending_numder:Number(item.transfer_qty) || 0,
                stock_entry_no:item.stock_entry_no
            }));
        
            // 发送更新请求
            const response = await axios.put(
                "http://localhost:5181/api/Inv_trf/Inv_othwr_Update",
                {
                    updateDto: {
                        trf_id: trf_order.trf_id,
                        trf_type: trf_order.trf_type,
                        trf_code: trf_order.trf_code,
                        trf_applicant: trf_order.trf_applicant,
                        trf_startdate: trf_order.trf_startdate,
                        trf_status: trf_order.trf_status,
                        warehouse_out_code: trf_order.warehouse_out_code,
                        warehouse_out_name: trf_order.warehouse_out_name,
                        warehouse_enter_code: trf_order.warehouse_enter_code,
                        warehouse_enter_name: trf_order.warehouse_enter_name,
            
                        update_by: trf_order.update_by,
                        update_time: trf_order.update_time
                    },
                    updateDtls: detailList
                },
                {
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                }
            );

            if (response.data > 0) {
                ElMessage.success("修改成功");
                selectedData.value = [];
                handleClose();
            } else {
                ElMessage.error("修改失败");
            }
        } catch (error) {
            console.error("修改出错:", error);
            ElMessage.error("修改过程中发生错误: " + (error.response?.data || error.message));
        }
    }

    // 加载修改的数据
    async function loadEditData() {
        axios.get("http://localhost:5181/api/Inv_trf/Inv_trf_SelectCode", {
            params: {
                trf_code: trf_code.value
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((res) => {
            const mainData = res.data[0];

            // 填充主表数据
            Object.assign(trf_order, {
                trf_id: mainData.trf_id,
                trf_code: mainData.trf_code,
                trf_type: mainData.trf_type,
                trf_applicant: mainData.trf_applicant,
                trf_startdate: mainData.trf_startdate,
                trf_status: mainData.trf_status,
                trf_audit_by: mainData.trf_audit_by,
                trf_audit_time: mainData.trf_audit_time,
                trf_audit_status: mainData.trf_audit_status,
                warehouse_out_code: mainData.warehouse_out_code,
                warehouse_out_name: mainData.warehouse_out_name,
                warehouse_enter_code: mainData.warehouse_enter_code,
                warehouse_enter_name: mainData.warehouse_enter_name,
            });

            // 加载仓库区域
            loadWarehouseZones();
            // 加载产品明细
            loadProductDetails();

            productCount();
        }).catch((res) => {
            console.log(res)
        })
    }

    // 加载仓库区域
    function loadWarehouseZones() {
        // 调出仓库区域
        axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
            params: {
                warehouse_code: trf_order.warehouse_out_code
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            outZones.value = result.data;
        });

        // 调入仓库区域
        axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
            params: {
                warehouse_code: trf_order.warehouse_enter_code
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            enterZones.value = result.data;
        });

    
    }

    // 加载产品明细数据
    function loadProductDetails() {
        axios.get("http://localhost:5181/api/Inv_trf/Inv_trf_SelectDetail", {
            params: {
                trf_code: trf_code.value
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then(async (result) => {
            const tempData = [];

            for (const item of result.data) {
                // 获取当前产品的库存
                const stockNumber = await StockSelect(
                    trf_order.warehouse_out_code,
                    item.pro_code
                );

                tempData.push({
                    ...item,
                    trfproddtl_id: item.trfproddtl_id,
                    stock_numder: stockNumber,
                    transfer_qty: item.inventory_numder,
                    out_location_name: item.out_location_name,
                    enter_location_name: item.enter_location_name,
                    stock_entry_no: item.stock_entry_no,
                    stock_name: item.pro_name,
                    stock_model: item.pro_model,
                    dict_code: item.unitmeas_id,
                });
            }

            selectedData.value = tempData;
        }).catch((error) => {
            console.error("加载产品明细失败:", error);
            ElMessage.error('加载产品明细失败');
        });
    }

    // 根据仓库编码和产品编码查询库存信息
    function StockSelect(warehouse_code, pro_code) {
        return axios.get("http://localhost:5181/api/Inv_Stock/GetinvStock", {
            params: {
                weahouse_code: warehouse_code,
                por_code: pro_code,
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((res) => {
            return res.data;
        }).catch((res) => {
            console.log(res);
        })
    }

    // 调出仓库变化
    const handleOutWarehouseChange = (selectedValue) => {
        const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
        trf_order.warehouse_out_name = selectedItem?.warehouse_name || "";

        if (selectedValue === trf_order.warehouse_enter_code) {
            ElMessage.warning('调出仓库和调入仓库不能相同');
            trf_order.warehouse_out_code = '';
            trf_order.warehouse_out_name = '';
        }

        // ✅ 新增：清空产品明细数据，防止库存错乱
        //selectedData.value = [];
    };


    // 调拨类型选择事件触发
    const handleSelectType = (value) => {
        const selectedItem = options.value.find(item => item.dict_value == value)
        trf_order.trf_type = selectedItem.dict_value;
    }

    function productAdd() {
        dialogTableVisible.value = true

        productFill();
    }



    // 移除选中的table控件数据
    const productDel = () => {
        if (selectedRows.value.length === 0) {
            ElMessage.warning('请先选择要移除的数据');
            return;
        }

        // 创建一个包含选中项的 stock_entry_no 和 pro_code 的数组
        const selectedEntries = selectedRows.value.map(item => ({
            stock_entry_no: item.stock_entry_no,
            pro_code: item.pro_code
        }));

        // 过滤掉被选中的项
        selectedData.value = selectedData.value.filter(item => {
            // 检查当前项的 stock_entry_no 和 pro_code 是否不在选中的数组中
            return !selectedEntries.some(
                selected =>
                    selected.stock_entry_no === item.stock_entry_no &&
                    selected.pro_code === item.pro_code
            );
        });

        if (selectedTable.value) {
            selectedTable.value.clearSelection();
        }
        selectedRows.value = [];
    };

    // 分页查询产品库存信息
    function productFill() {
    
        axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All", {
            params: {
                weahouse_code: trf_order.warehouse_out_code,
                pro_code: productcode.value,
                dict_code: dict_code.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            productData.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    }

    // 查询产品库存总数
    const productCount = () => {
    
        axios.get("http://localhost:5181/api/Inv_Stock/Get_Select__stock_Count", {
            params: {
                weahouse_code: trf_order.warehouse_out_code,
                pro_code: productcode.value,
                dict_code: dict_code.value,
            },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }).then((result) => {
        
            pageCount.value = result.data || 0
        
        }).catch((err) => {
            console.error(err);
        });
    };

    function handleSizeChange(val) {
        pageSize.value = val;
        productFill();
    }

    function handleCurrentChange(val) {
        currentPage.value = val;
        productFill();
    }

    // 查询计量单位
    function getMeasure() {
        axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
            params: {
                dict_type: "db_measure"
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            measureOptios.value = result.data
            measureOptios.value = [{
                dict_value: "0", dict_label: "请选择单位"
            }, ...result.data]
        }).catch((err) => {
            console.info(err)
        });
    }

    // 根据计量单位id返回计量单位名称
    function measureValue(row) {
        if (!row) return "无";
        const unit = measureOptios.value.find((item) => item.dict_value == row);
        return unit ? unit.dict_label : "无";
    }

    // 查询调拨类型
    function getTransferTypes() {
        axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
            params: {
                dict_type: "inv_trf"
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            options.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    }

    // 查询仓库信息
    function getWarehouses() {
        axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        }).then((res) => {
            warehouses.value = res.data;
        }).catch((res) => {
            console.log(res)
        })
    }

    const handleEnterWarehouseChange = (selectedValue) => {
        const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
        trf_order.warehouse_enter_name = selectedItem?.warehouse_name || "";

        if (selectedValue === trf_order.warehouse_out_code) {
            ElMessage.warning('调入仓库和调出仓库不能相同');
            trf_order.warehouse_enter_code = '';
            trf_order.warehouse_enter_name = '';
        }
    };

    // 根据选择条件查询产品库存信息
    function productSearch() {
        productFill()
        productCount()
    }

    // 重置条件查询
    function productReset() {
        productcode.value = ""
        dict_code.value = "0"
        productFill()
        productCount()
    }

    // 表格选择变化时的处理函数
    const handleSelectionChange = (val) => {
        selectedProducts.value = val;
    };

    // 点击确定存储选择的产品数据
    const handleConfirmSelection = () => {
        selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
            ...item,
            transfer_qty: Number(0),
            out_location_code: "",
            out_location_name: "",
            enter_location_code: "",
            enter_location_name: "",
        }))]
        dialogTableVisible.value = false
        multipleTableRef.value.clearSelection()
    }

    // 表格选择变化时处理数据
    const handleSelectedChange = (val) => {
        selectedRows.value = val;
    };

    // 判断以添加过的产品数据不能再次添加
    const isDisabled = (row) => {
        return !selectedData.value.some(
            item => item.pro_code === row.pro_code && item.stock_entry_no === row.stock_entry_no
        );
    };

    // 退出页面
    function handleClose() {
        router.push('/main/Inv/InvTrf');
    }

    onMounted(() => {
        // 加载修改数据
        loadEditData();

        getMeasure();
        getTransferTypes();
        getWarehouses();
    
    });
    </script>

    <style scoped>
    .transfer-edit-form {
        padding: 20px;
        background-color: #fff;
    }

    .section {
        margin-bottom: 30px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        padding: 20px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    }

    .section-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
    }

    .button-group {
        display: flex;
        justify-content: flex-end;
        margin-top: 20px;
    }
    </style>